﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.IRepository.IService;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Enum;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.Models.PDA;
using DFGK_WMS.Repository.Service;
using Microsoft.EntityFrameworkCore;
using NetTaste;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;
using NPOI.SS.UserModel;
using NPOI.XWPF.UserModel;
using SqlSugar;

namespace DFGK_WMS.Repository
{
    public class TReceivingBillRepository : BaseRepository<Model.Models.TReceivingBill>, ITReceivingBillRepository
    {
        public IBarCodeRuleRepository BarCodeRuleRepository { get; }
        public ITReceivingOrderDetailRepository TReceivingOrderDetail { get; }
        public IStackingStorageService StackingStorageService { get; }

        public TReceivingBillRepository(DFGK_DB context, IMapper mapper, IBarCodeRuleRepository barCodeRuleRepository, ITReceivingOrderDetailRepository tReceivingOrderDetail, IStackingStorageService stackingStorageService) : base(context, mapper)
        {
            BarCodeRuleRepository = barCodeRuleRepository;
            TReceivingOrderDetail = tReceivingOrderDetail;
            StackingStorageService = stackingStorageService;
        }

        /// <summary>
        /// 逻辑分区
        /// </summary>
        /// <returns></returns>
        public List<TDictItem> GetDictItems()
        {
            var list = Context.TDictItems
                .Where(x => x.TypeId == 41);

            if (list == null)
            {
                return null;
            }

            return list.ToList();
        }

        /// <summary>
        /// 添加收货单
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddReceivingBill(Model.Models.TReceivingBill m, out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    message = "";
                    //供应商信息
                    var sobj = Context.TSuppliers.Find(m.SupplierId);
                    if (sobj != null)
                    {
                        m.SupplierName = sobj.Name;
                    }

                    //仓库信息
                    var wobj = Context.TWarehouses.Find(m.WarehouseId);
                    if (wobj != null && wobj.Status==1)
                    {
                        m.WarehouseName = wobj.Name;
                        m.WarehouseCode = wobj.Code;
                    }
                    else
                    {
                        message = "库房不存在或已被禁用！";
                        return false;
                    }

                    //初始化状态
                    m.Status = 0;
                    //默认收货数量
                    m.ReceivedQTY = 0;
                    m.BeginDate = DateTime.Now;

                    #region 审计字段
                    m.CreateUserId = m.NowUserId;
                    m.CreateUserName = m.NowUserRealName;
                    m.CreateDate = DateTime.Now;
                    Context.TReceivingBills.Add(m);
                    Context.SaveChanges();
                    #endregion
                    foreach (var item in m.BillDetailList)
                    {
                        //供应商
                        item.SupplierId = m.SupplierId;
                        item.SupplierName = m.SupplierName;
                        //关联单号
                        item.BillNo = m.BillNo;
                        item.BillId = m.Id;
                        //初始化状态
                        item.Status = 0;
                        //创建日期
                        item.CreateDate = DateTime.Now;
                        Context.TReceivingBillDetails.Add(item);
                    }
                    Context.SaveChanges();
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 收货入库(弃用)
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddReceivingOrderDateil(ReceivingBillOrderDto m, out string message)
        {
            message = "";
            using (var tran = Context.Database.BeginTransaction())
                try
                {
                    var receivingBills = Context.TReceivingBills.FirstOrDefault(r => r.Id == m.Id);
                    if (receivingBills == null)
                    {
                        message = "收货单不存在";
                        return false;
                    }
                    decimal count = 0;
                    foreach (var item in m.ReceivingBillOrderDetailDtos)
                    {
                        if (item.ReceivedQty < 0)
                        {
                            message = "收货数量不能小于0";
                            return false;
                        }
                        var r = Context.TReceivingBillDetails.Find(item.ReceivingBillDetailId);
                        if (r is null)
                        {
                            message = "收货单明细不存在";
                            return false;
                        }
                        else
                        {
                            if (r.Qty >= item.ReceivedQty && (r.ReceivedQty + item.ReceivedQty) <= r.Qty)
                            {
                                r.ReceivedQty += item.ReceivedQty;
                                count += r.ReceivedQty;
                                if (r.Price is not null || r.Price >= 0)
                                {
                                    receivingBills.TotalPrice += (decimal)r.Price * item.ReceivedQty;
                                }
                            }
                            else
                            {
                                message = "收货数量不能大于物料数量";
                                return false;
                            }
                            Context.TReceivingBillDetails.Update(r);
                            //Context.SaveChanges();
                        }
                    }
                    string receordercode = BarCodeRuleRepository.GetBarCodeSample(1);
                    if (string.IsNullOrEmpty(receordercode) || receordercode.Length == 0)
                    {
                        //trans.Rollback();
                        message = "入库单编码不存在或已被禁用！";
                        return false;
                    }
                    bool reresult = false;
                    if (count == receivingBills.TotalQty)
                    {
                        receivingBills.Status = 2;
                        receivingBills.EndDate = DateTime.Now;
                        foreach (var item in m.ReceivingBillOrderDetailDtos)
                        {
                            if (item.ReceivedQty == 0)
                            {
                                continue;
                            }
                            TReceivingOrderDetail receivingOrder = new TReceivingOrderDetail();
                            receivingOrder.OrderSn = receordercode;
                            //本地入库
                            receivingOrder.BillType = 1;
                            //receivingOrder.WarehouseId = m.Wid;
                            //receivingOrder.SupplierId = m.Suppid;
                            receivingOrder.MaterialId = item.MaterialId;
                            receivingOrder.OwnerId = item.OwerId;
                            receivingOrder.BatchNo = item.MaterialBatchNo;
                            //订单来源默认手动创建
                            receivingOrder.SourceType = 0;
                            //质检状态默认为合格
                            receivingOrder.QualityState = 1;
                            //质量状态
                            receivingOrder.Status = 3;
                            receivingOrder.ReceivedQty = 0;
                            receivingOrder.PackagedQty = 0;
                            receivingOrder.PackQty = 0;
                            receivingOrder.BatchNoExplain = item.BatchNoExplain;
                            receivingOrder.OutFactoryDate = item.OutFactoryDate;
                            receivingOrder.ProduceFactory = item.ProduceFactory;
                            receivingOrder.ProductDate = item.ProductDate;
                            receivingOrder.ExpireDate = item.ExpireDate;
                            receivingOrder.Remark = item.Remark;
                            receivingOrder.Qty = item.ReceivedQty;
                            #region 审计字段
                            receivingOrder.CreateUserId = m.NowUserId;
                            receivingOrder.CreateUserName = m.NowUserRealName;
                            receivingOrder.CreateDate = DateTime.Now;
                            //receivingOrder.ModifyUserId = m.NowUserId;
                            //receivingOrder.ModifyUserName = m.NowUserRealName;
                            //receivingOrder.ModifyDate = DateTime.Now;
                            receivingOrder.AuditUserId = m.NowUserId;
                            receivingOrder.AuditUserName = m.NowUserRealName;
                            receivingOrder.AuditDate = DateTime.Now;
                            receivingOrder.SubmitUserId = m.NowUserId;
                            receivingOrder.SubmitUserName = m.NowUserRealName;
                            receivingOrder.SubmitDate = DateTime.Now;
                            //采购订单行项目类型
                            receivingOrder.PurOrderLineType = 0;
                            receivingOrder.StackedQty = 0;
                            reresult = AddTReceivingOrderDetail(receivingOrder, out message);
                            #endregion
                        }
                        if (reresult == false)
                        {
                            tran.Rollback();
                            return false;
                        }
                        Context.TReceivingBills.Update(receivingBills);
                        //Context.SaveChanges();
                    }
                    if (count < receivingBills.TotalQty)
                    {
                        receivingBills.Status = 1;
                        #region 
                        foreach (var item in m.ReceivingBillOrderDetailDtos)
                        {
                            if (item.ReceivedQty == 0)
                            {
                                continue;
                            }
                            TReceivingOrderDetail receivingOrder = new TReceivingOrderDetail();
                            receivingOrder.OrderSn = receordercode;
                            //本地入库
                            receivingOrder.BillType = 1;
                            //receivingOrder.WarehouseId = m.Wid;
                            //receivingOrder.SupplierId = m.Suppid;
                            receivingOrder.MaterialId = item.MaterialId;
                            receivingOrder.OwnerId = item.OwerId;
                            receivingOrder.BatchNo = item.MaterialBatchNo;
                            //订单来源默认手动创建
                            receivingOrder.SourceType = 0;
                            //质检状态默认为合格
                            receivingOrder.QualityState = 1;
                            //质量状态
                            receivingOrder.Status = 3;
                            receivingOrder.ReceivedQty = 0;
                            receivingOrder.PackagedQty = 0;
                            receivingOrder.PackQty = 0;
                            receivingOrder.BatchNoExplain = item.BatchNoExplain;
                            receivingOrder.OutFactoryDate = item.OutFactoryDate;
                            receivingOrder.ProduceFactory = item.ProduceFactory;
                            receivingOrder.ProductDate = item.ProductDate;
                            receivingOrder.ExpireDate = item.ExpireDate;
                            receivingOrder.Remark = item.Remark;
                            receivingOrder.Qty = item.ReceivedQty;
                            #region 审计字段
                            receivingOrder.CreateUserId = m.NowUserId;
                            receivingOrder.CreateUserName = m.NowUserRealName;
                            receivingOrder.CreateDate = DateTime.Now;
                            //receivingOrder.ModifyUserId = m.NowUserId;
                            //receivingOrder.ModifyUserName = m.NowUserRealName;
                            //receivingOrder.ModifyDate = DateTime.Now;
                            receivingOrder.AuditUserId = m.NowUserId;
                            receivingOrder.AuditUserName = m.NowUserRealName;
                            receivingOrder.AuditDate = DateTime.Now;
                            receivingOrder.SubmitUserId = m.NowUserId;
                            receivingOrder.SubmitUserName = m.NowUserRealName;
                            receivingOrder.SubmitDate = DateTime.Now;
                            //采购订单行项目类型
                            receivingOrder.PurOrderLineType = 0;
                            receivingOrder.StackedQty = 0;
                            reresult = AddTReceivingOrderDetail(receivingOrder, out message);
                            #endregion
                        }
                        if (reresult == false)
                        {
                            tran.Rollback();
                            return false;
                        }
                        #endregion
                        Context.TReceivingBills.Update(receivingBills);
                    }
                    Context.SaveChanges();
                    //提交事务
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }

        }


        /// <summary>
        /// PC/PDA收货入库
        /// </summary>
        /// <param name="receivingBillOrderDto"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddPDAReceivingOrderDateil(ReceivingBillOrderDto m, out string message)
        {
            message = "";
            using (var tran = Context.Database.BeginTransaction())
                try
                {
                    var receivingBills = Context.TReceivingBills.FirstOrDefault(r => r.Id == m.Id);
                    if (receivingBills == null)
                    {
                        message = "收货单不存在";
                        Context.TLogs.Add(new TLog()
                        {
                            LogType = 1,
                            ActionType = 0,
                            Description = "收货单不存在",
                            CreateDate = DateTime.Now
                        });
                        Context.SaveChanges();
                        return false;
                    }
                    var rbd = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == receivingBills.Id).ToList();

                    foreach (var item in rbd)
                    {
                        if (item.ReceivedQty <= 0)
                        {
                            continue;
                        }
                        receivingBills.ReceivedQTY = receivingBills.ReceivedQTY.GetValueOrDefault() + item.ReceivedQty;
                    }
                    string receordercode = "";

                    //查看收货单已收货数量是否是0 （是的话创建一个入库单编号 不是0查询出入库单编号）
                    if (receivingBills.ReceivedQTY == 0 || receivingBills.ReceivedQTY is null)
                    {
                        receivingBills.AreaId = m.StoreId;
                        receivingBills.AreaId = m.AreaId;
                        receivingBills.AreaName = m.AreaName;
                        receivingBills.AreaCode = m.AreaCode;
                        Context.TReceivingBills.Update(receivingBills);
                        if (Context.SaveChanges() <= 0)
                        {
                            message = "修改库区信息失败";
                            tran.Rollback();
                            return false;
                        }
                        receordercode = BarCodeRuleRepository.GetBarCodeSample(1);
                        if (string.IsNullOrEmpty(receordercode) || receordercode.Length == 0)
                        {
                            message = "入库单编码不存在或已被禁用！";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "入库单编码不存在或已被禁用",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                    }
                    else
                    {
                        if (receivingBills.AreaId != m.AreaId)
                        {
                            message = "库位不在一个库房中";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "库位不在一个库房中",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                        var rece = Context.TReceivingOrderDetails.AsNoTracking().FirstOrDefault(r => r.ReceivingBillId == receivingBills.Id);
                        if (rece is null)
                        {
                            message = "入库单编码不存在！";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "入库单编码不存在",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                        receordercode = rece.OrderSn;
                    }
                    decimal count = 0;//计算数量
                    foreach (var item in m.ReceivingBillOrderDetailDtos)
                    {
                        if (item.ReceivedQty < 0)
                        {
                            message = "收货数量不能小于0";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "收货数量不能小于0",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                        var r = Context.TReceivingBillDetails.Find(item.ReceivingBillDetailId);
                        if (r is null)
                        {
                            message = "收货单明细不存在";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "收货单明细不存在",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                        else
                        {
                            if (item.PalletBarcode is null || string.IsNullOrEmpty(item.PalletBarcode) || item.MaterialBatchNo is null || string.IsNullOrEmpty(item.MaterialBatchNo))
                            {
                                continue;
                            }
                            r.storeLocationId = item.StoreLocationCode;
                            Context.TReceivingBillDetails.Update(r);
                            if (Context.SaveChanges() <= 0)
                            {
                                message = "修改收获单明细仓位失败";
                                tran.Rollback();
                                return false;
                            }

                            if (r.Qty >= item.ReceivedQty && (r.ReceivedQty + item.ReceivedQty) <= r.Qty)
                            {
                                r.ReceivedQty += item.ReceivedQty;
                                count += item.ReceivedQty;
                                if (r.Price is not null || r.Price >= 0)
                                {
                                    receivingBills.TotalPrice += (decimal)r.Price * item.ReceivedQty;
                                }
                            }
                            else
                            {
                                message = "收货数量不能大于物料数量";
                                Context.TLogs.Add(new TLog()
                                {
                                    LogType = 1,
                                    ActionType = 0,
                                    Description = "收货数量不能大于物料数量",
                                    CreateDate = DateTime.Now
                                });
                                Context.SaveChanges();
                                tran.Rollback();
                                return false;
                            }
                            Context.TReceivingBillDetails.Update(r);
                            //Context.SaveChanges();
                        }
                    }
                    TReceivingOrderDetail receivingOrder = new TReceivingOrderDetail();
                    bool reresult = false;
                    var res = Context.TReceivingBillDetails.Where(x => x.BillId == receivingBills.Id).ToList();
                    var cellList = Context.TCells.AsNoTracking().ToList();
                    // 计算收货数量
                    foreach (var item in rbd)
                    {
                        count += item.ReceivedQty;
                    }
                    if (count == receivingBills.TotalQty)
                    {
                        receivingBills.Status = 2;
                        receivingBills.EndDate = DateTime.Now;

                        foreach (var item in m.ReceivingBillOrderDetailDtos)
                        {
                            if (item.ReceivedQty == 0 || (item.PalletBarcode is null || string.IsNullOrEmpty(item.PalletBarcode) || string.IsNullOrEmpty(item.PalletBarcode) || item.MaterialBatchNo is null))
                            {
                                continue;
                            }
                            var cell = cellList.Where(c => c.Code == item.StoreLocationCode).FirstOrDefault();
                            if (cell is null)
                            {
                                message = "未找到此库位";
                                tran.Rollback();
                                return false;
                            }
                            if (cell.AreaId != m.AreaId)
                            {
                                message = "库位不在一个库房中";
                                tran.Rollback();
                                return false;
                            }
                            #region 添加入库单数据
                            receivingOrder.OrderSn = receordercode;
                            //本地入库
                            receivingOrder.BillType = 1;
                            receivingOrder.WarehouseId = m.StoreId;
                            receivingOrder.AreaCode = m.AreaCode;
                            receivingOrder.AreaName = m.AreaName;
                            receivingOrder.MaterialId = item.MaterialId;
                            receivingOrder.OwnerId = item.OwerId;
                            receivingOrder.BatchNo = item.MaterialBatchNo;
                            receivingOrder.MaterialCode = item.MaterialCode;
                            receivingOrder.MaterialName = item.MaterialName;
                            receivingOrder.DeptName = item.DeptName;
                            //订单来源默认手动创建
                            receivingOrder.SourceType = 0;
                            //质检状态默认为合格
                            receivingOrder.QualityState = 1;
                            //质量状态
                            receivingOrder.Status = 3;
                            receivingOrder.ReceivedQty = 0;
                            receivingOrder.PackagedQty = 0;
                            receivingOrder.PackQty = 0;
                            receivingOrder.BatchNoExplain = item.BatchNoExplain;
                            receivingOrder.OutFactoryDate = item.OutFactoryDate;
                            receivingOrder.ProduceFactory = item.ProduceFactory;
                            receivingOrder.ProductDate = item.ProductDate;
                            receivingOrder.ExpireDate = item.ExpireDate;
                            receivingOrder.Remark = item.Remark;
                            receivingOrder.Qty = item.ReceivedQty;
                            receivingOrder.storeLocationId = cell.Code;
                            receivingOrder.relationId = item.CheckInfoId.GetValueOrDefault();
                            #region 审计字段
                            receivingOrder.CreateUserId = m.NowUserId;
                            receivingOrder.CreateUserName = m.NowUserRealName;
                            receivingOrder.CreateDate = DateTime.Now;
                            //receivingOrder.ModifyUserId = m.NowUserId;
                            //receivingOrder.ModifyUserName = m.NowUserRealName;
                            //receivingOrder.ModifyDate = DateTime.Now;
                            receivingOrder.AuditUserId = m.NowUserId;
                            receivingOrder.AuditUserName = m.NowUserRealName;
                            receivingOrder.AuditDate = DateTime.Now;
                            receivingOrder.SubmitUserId = m.NowUserId;
                            receivingOrder.SubmitUserName = m.NowUserRealName;
                            receivingOrder.SubmitDate = DateTime.Now;
                            receivingOrder.ReceivingBillId = receivingBills.Id;
                            #endregion
                            //采购订单行项目类型
                            receivingOrder.PurOrderLineType = 0;
                            receivingOrder.StackedQty = 0;
                            reresult = AddTReceivingOrderDetail(receivingOrder, out message);
                            if (reresult == false)
                            {
                                message = "添加入库单失败" + message;
                                Context.TLogs.Add(new TLog()
                                {
                                    LogType = 1,
                                    ActionType = 4,
                                    Description = message,
                                    CreateDate = DateTime.Now
                                });
                                Context.SaveChanges();
                                tran.Rollback();
                                return false;
                            }
                            #endregion
                            var receiving = Context.TReceivingOrderDetails.First(r => r.Id == receivingOrder.Id);
                            PalletTallyInputModel palletTallyInputModel = new PalletTallyInputModel();
                            palletTallyInputModel.PalletBarcode = item.PalletBarcode;
                            palletTallyInputModel.TotalNum = item.ReceivedQty;
                            palletTallyInputModel.OrderDetailId = receiving.Id;
                            palletTallyInputModel.WarehouseId = receiving.WarehouseId;
                            palletTallyInputModel.LogicPartCode = receiving.LogicalPartCode;
                            palletTallyInputModel.PalletPackage.MaterialCode = receiving.MaterialCode;
                            palletTallyInputModel.storeLocationId = cell.Id;
                            palletTallyInputModel.storeLocationCode = cell.Code;
                            palletTallyInputModel.remark = cell.Name;
                            palletTallyInputModel.storeId = m.StoreId;
                            reresult = StackingStorageService.BuildCreateStackingStorageEF(out message, palletTallyInputModel);
                            if (!reresult)
                            {
                                if (message is null)
                                {
                                    message = "保存组箱数据失败";
                                }
                                else
                                {
                                    message = message;
                                }
                                Context.TLogs.Add(new TLog()
                                {
                                    LogType = 1,
                                    ActionType = 4,
                                    Description = message,
                                    CreateDate = DateTime.Now
                                });
                                Context.SaveChanges();
                                tran.Rollback();
                                return false;
                            }
                        }
                        
                        Context.TReceivingBills.Update(receivingBills);
                        //Context.SaveChanges();
                    }
                    if (count < receivingBills.TotalQty)
                    {
                        receivingBills.Status = 1;
                        foreach (var item in m.ReceivingBillOrderDetailDtos)
                        {
                            if (item.ReceivedQty == 0 || (item.PalletBarcode is null || string.IsNullOrEmpty(item.PalletBarcode) || string.IsNullOrEmpty(item.PalletBarcode) || item.MaterialBatchNo is null))
                            {
                                continue;
                            }
                            var cell = cellList.Where(c => c.Code == item.StoreLocationCode).FirstOrDefault();
                            if (cell is null)
                            {
                                message = "未找到此库位";
                                tran.Rollback();
                                return false;
                            }
                            if (cell.AreaId != m.AreaId)
                            {
                                message = "库位不在一个库房中";
                                tran.Rollback();
                                return false;
                            }
                            #region 添加入库单数据
                            receivingOrder.OrderSn = receordercode;
                            //本地入库
                            receivingOrder.BillType = 1;
                            receivingOrder.WarehouseId = m.StoreId;
                            receivingOrder.AreaCode = m.AreaCode;
                            receivingOrder.AreaName = m.AreaName;
                            //receivingOrder.SupplierId = m.Suppid;
                            receivingOrder.MaterialId = item.MaterialId;
                            receivingOrder.MaterialCode = item.MaterialCode;
                            receivingOrder.MaterialName = item.MaterialName;
                            receivingOrder.OwnerId = item.OwerId;
                            receivingOrder.BatchNo = item.MaterialBatchNo;
                            receivingOrder.DeptName = item.DeptName;
                            //订单来源默认手动创建
                            receivingOrder.SourceType = 0;
                            //质检状态默认为合格
                            receivingOrder.QualityState = 1;
                            //质量状态
                            receivingOrder.Status = 3;
                            receivingOrder.ReceivedQty = 0;
                            receivingOrder.PackagedQty = 0;
                            receivingOrder.PackQty = 0;
                            receivingOrder.BatchNoExplain = item.BatchNoExplain;
                            receivingOrder.OutFactoryDate = item.OutFactoryDate;
                            receivingOrder.ProduceFactory = item.ProduceFactory;
                            receivingOrder.ProductDate = item.ProductDate;
                            receivingOrder.ExpireDate = item.ExpireDate;
                            receivingOrder.Remark = item.Remark;
                            receivingOrder.Qty = item.ReceivedQty;
                            receivingOrder.storeLocationId = cell.Code;
                            receivingOrder.relationId = item.CheckInfoId.GetValueOrDefault();
                            #region 审计字段
                            receivingOrder.CreateUserId = m.NowUserId;
                            receivingOrder.CreateUserName = m.NowUserRealName;
                            receivingOrder.CreateDate = DateTime.Now;
                            //receivingOrder.ModifyUserId = m.NowUserId;
                            //receivingOrder.ModifyUserName = m.NowUserRealName;
                            //receivingOrder.ModifyDate = DateTime.Now;
                            receivingOrder.AuditUserId = m.NowUserId;
                            receivingOrder.AuditUserName = m.NowUserRealName;
                            receivingOrder.AuditDate = DateTime.Now;
                            receivingOrder.SubmitUserId = m.NowUserId;
                            receivingOrder.SubmitUserName = m.NowUserRealName;
                            receivingOrder.SubmitDate = DateTime.Now;
                            receivingOrder.ReceivingBillId = receivingBills.Id;
                            #endregion
                            //采购订单行项目类型
                            receivingOrder.PurOrderLineType = 0;
                            receivingOrder.StackedQty = 0;
                            reresult = AddTReceivingOrderDetail(receivingOrder, out message);

                            if (reresult == false)
                            {
                                message = "添加入库单失败" + message;
                                Context.TLogs.Add(new TLog()
                                {
                                    LogType = 1,
                                    ActionType = 4,
                                    Description = message,
                                    CreateDate = DateTime.Now
                                });
                                Context.SaveChanges();
                                tran.Rollback();
                                return false;
                            }
                            #endregion
                            var receiving = Context.TReceivingOrderDetails.First(r => r.Id == receivingOrder.Id);
                            PalletTallyInputModel palletTallyInputModel = new PalletTallyInputModel();
                            palletTallyInputModel.PalletBarcode = item.PalletBarcode;
                            palletTallyInputModel.TotalNum = item.ReceivedQty;
                            palletTallyInputModel.OrderDetailId = receiving.Id;
                            palletTallyInputModel.WarehouseId = receiving.WarehouseId;
                            palletTallyInputModel.LogicPartCode = receiving.LogicalPartCode;
                            palletTallyInputModel.PalletPackage.MaterialCode = receiving.MaterialCode;
                            palletTallyInputModel.storeLocationId = cell.Id;
                            palletTallyInputModel.storeLocationCode = cell.Code;
                            palletTallyInputModel.remark = cell.Name;
                            palletTallyInputModel.storeId = m.StoreId;
                            reresult = StackingStorageService.BuildCreateStackingStorageEF(out message, palletTallyInputModel);
                            if (!reresult)
                            {
                                if (message is null)
                                {
                                    message = "保存组箱数据失败";
                                }
                                else
                                {
                                    message = message;
                                }
                                Context.TLogs.Add(new TLog()
                                {
                                    LogType = 1,
                                    ActionType = 4,
                                    Description = message,
                                    CreateDate = DateTime.Now
                                });
                                Context.SaveChanges();
                                tran.Rollback();
                                return false;
                            }
                        }
                        Context.TReceivingBills.Update(receivingBills);
                    }
                    Context.SaveChanges();
                    //提交事务
                    tran.Commit();

                    return true;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    Context.TLogs.Add(new TLog()
                    {
                        LogType = 1,
                        ActionType = 0,
                        Description = message,
                        CreateDate = DateTime.Now
                    });
                    Context.SaveChanges();
                    throw;
                }
        }

        /// <summary>
        /// 无网的pda收货入库
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddPDAReceivingOrderDateilNoNet(ReceivingBillOrderDto m, out string message)
        {
            message = "";
            using (var tran = Context.Database.BeginTransaction())
                try
                {
                    var receivingBills = Context.TReceivingBills.FirstOrDefault(r => r.Id == m.Id);
                    if (receivingBills == null)
                    {
                        message = "收货单不存在";
                        Context.TLogs.Add(new TLog()
                        {
                            LogType = 1,
                            ActionType = 0,
                            Description = "收货单不存在",
                            CreateDate = DateTime.Now
                        });
                        Context.SaveChanges();
                        return false;
                    }
                    var rbd = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == receivingBills.Id).ToList();

                    foreach (var item in rbd)
                    {
                        
                        if (item.ReceivedQty <= 0)
                        {
                            continue;
                        }
                        receivingBills.ReceivedQTY = receivingBills.ReceivedQTY.GetValueOrDefault() + item.ReceivedQty;
                    }
                    string receordercode = "";

                    //查看收货单已收货数量是否是0 （是的话创建一个入库单编号 不是0查询出入库单编号）
                    if (receivingBills.ReceivedQTY == 0 || receivingBills.ReceivedQTY is null)
                    {
                        receivingBills.WarehouseId = m.StoreId;
                        receivingBills.AreaId = m.AreaId;
                        receivingBills.AreaName = m.AreaName;
                        receivingBills.AreaCode = m.AreaCode;
                        Context.TReceivingBills.Update(receivingBills);
                        if (Context.SaveChanges() <= 0)
                        {
                            message = "修改库区信息失败";
                            tran.Rollback();
                            return false;
                        }
                        receordercode = BarCodeRuleRepository.GetBarCodeSample(1);
                        if (string.IsNullOrEmpty(receordercode) || receordercode.Length == 0)
                        {
                            message = "入库单编码不存在或已被禁用！";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "入库单编码不存在或已被禁用",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                    }
                    else
                    {
                        if (receivingBills.AreaId != m.AreaId)
                        {
                            message = "不在一个库房";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "不在一个库房",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                        var rece = Context.TReceivingOrderDetails.AsNoTracking().FirstOrDefault(r => r.ReceivingBillId == receivingBills.Id);
                        if (rece is null)
                        {
                            message = "入库单编码不存在！";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "入库单编码不存在",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                        receordercode = rece.OrderSn;
                    }
                    decimal count = 0;//计算数量
                    foreach (var item in m.ReceivingBillOrderDetailDtos)
                    {
                        if (item.ReceivedQty < 0)
                        {
                            message = "收货数量不能小于0";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "收货数量不能小于0",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                        var r = Context.TReceivingBillDetails.Find(item.ReceivingBillDetailId);
                        if (r is null)
                        {
                            message = "收货单明细不存在";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "收货单明细不存在",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                        else
                        {
                            if (item.PalletBarcode is null || string.IsNullOrEmpty(item.PalletBarcode))
                            {
                                continue;
                            }
                            item.MaterialName = r.MaterialName;
                            item.MaterialBatchNo = r.BatchNo;
                            item.DeptName = r.deptName;
                            item.CheckInfoId = r.checkInfoId;
                            r.storeLocationId = item.StoreLocationCode;
                            Context.TReceivingBillDetails.Update(r);
                            if (Context.SaveChanges() <= 0)
                            {
                                message = "修改收获单明细仓位失败";
                                tran.Rollback();
                                return false;
                            }

                            if (r.Qty >= item.ReceivedQty && (r.ReceivedQty + item.ReceivedQty) <= r.Qty)
                            {
                                r.ReceivedQty += item.ReceivedQty;
                                count += item.ReceivedQty;
                                if (r.Price is not null || r.Price >= 0)
                                {
                                    receivingBills.TotalPrice += (decimal)r.Price * item.ReceivedQty;
                                }
                            }
                            else
                            {
                                message = "收货数量不能大于物料数量";
                                Context.TLogs.Add(new TLog()
                                {
                                    LogType = 1,
                                    ActionType = 0,
                                    Description = "收货数量不能大于物料数量",
                                    CreateDate = DateTime.Now
                                });
                                Context.SaveChanges();
                                tran.Rollback();
                                return false;
                            }
                            Context.TReceivingBillDetails.Update(r);
                            Context.SaveChanges();
                        }
                    }
                    TReceivingOrderDetail receivingOrder = new TReceivingOrderDetail();
                    bool reresult = false;
                    var res = Context.TReceivingBillDetails.Where(x => x.BillId == receivingBills.Id).ToList();
                    var cellList = Context.TCells.AsNoTracking().ToList();
                    // 计算收货数量
                    foreach (var item in rbd)
                    {
                        count += item.ReceivedQty;
                    }
                    if (count == receivingBills.TotalQty)
                    {
                        receivingBills.Status = 2;
                        receivingBills.EndDate = DateTime.Now;

                        foreach (var item in m.ReceivingBillOrderDetailDtos)
                        {

                            if (item.ReceivedQty == 0 || (item.PalletBarcode is null || string.IsNullOrEmpty(item.PalletBarcode) || string.IsNullOrEmpty(item.PalletBarcode)))
                            {
                                continue;
                            }
                            var cell = cellList.Where(c => c.Code == item.StoreLocationCode).FirstOrDefault();
                            if (cell is null)
                            {
                                message = "未找到此库位";
                                tran.Rollback();
                                return false;
                            }
                            if (cell.AreaId != m.AreaId)
                            {
                                message = "库位不在一个库房中";
                                tran.Rollback();
                                return false;
                            }
                            #region 添加入库单数据
                            receivingOrder.OrderSn = receordercode;
                            //本地入库
                            receivingOrder.BillType = 1;
                            receivingOrder.WarehouseId = m.StoreId;
                            receivingOrder.AreaCode = m.AreaCode;
                            receivingOrder.AreaName = m.AreaName;
                            receivingOrder.MaterialId = item.MaterialId;
                            receivingOrder.OwnerId = item.OwerId;
                            receivingOrder.BatchNo = item.MaterialBatchNo;
                            receivingOrder.MaterialCode = item.MaterialCode;
                            receivingOrder.MaterialName = item.MaterialName;
                            receivingOrder.DeptName = item.DeptName;
                            //订单来源默认手动创建
                            receivingOrder.SourceType = 0;
                            //质检状态默认为合格
                            receivingOrder.QualityState = 1;
                            //质量状态
                            receivingOrder.Status = 3;
                            receivingOrder.ReceivedQty = 0;
                            receivingOrder.PackagedQty = 0;
                            receivingOrder.PackQty = 0;
                            receivingOrder.BatchNoExplain = item.BatchNoExplain;
                            receivingOrder.OutFactoryDate = item.OutFactoryDate;
                            receivingOrder.ProduceFactory = item.ProduceFactory;
                            receivingOrder.ProductDate = item.ProductDate;
                            receivingOrder.ExpireDate = item.ExpireDate;
                            receivingOrder.Remark = item.Remark;
                            receivingOrder.Qty = item.ReceivedQty;
                            receivingOrder.storeLocationId = cell.Code;
                            receivingOrder.relationId = item.CheckInfoId.GetValueOrDefault();
                            #region 审计字段
                            receivingOrder.CreateUserId = m.NowUserId;
                            receivingOrder.CreateUserName = m.NowUserRealName;
                            receivingOrder.CreateDate = DateTime.Now;
                            //receivingOrder.ModifyUserId = m.NowUserId;
                            //receivingOrder.ModifyUserName = m.NowUserRealName;
                            //receivingOrder.ModifyDate = DateTime.Now;
                            receivingOrder.AuditUserId = m.NowUserId;
                            receivingOrder.AuditUserName = m.NowUserRealName;
                            receivingOrder.AuditDate = DateTime.Now;
                            receivingOrder.SubmitUserId = m.NowUserId;
                            receivingOrder.SubmitUserName = m.NowUserRealName;
                            receivingOrder.SubmitDate = DateTime.Now;
                            receivingOrder.ReceivingBillId = receivingBills.Id;
                            #endregion
                            //采购订单行项目类型
                            receivingOrder.PurOrderLineType = 0;
                            receivingOrder.StackedQty = 0;
                            reresult = AddTReceivingOrderDetail(receivingOrder, out message);
                            if (reresult == false)
                            {
                                message = "添加入库单失败" + message;
                                Context.TLogs.Add(new TLog()
                                {
                                    LogType = 1,
                                    ActionType = 4,
                                    Description = message,
                                    CreateDate = DateTime.Now
                                });
                                Context.SaveChanges();
                                tran.Rollback();
                                return false;
                            }
                            #endregion
                            var receiving = Context.TReceivingOrderDetails.First(r => r.Id == receivingOrder.Id);
                            PalletTallyInputModel palletTallyInputModel = new PalletTallyInputModel();
                            palletTallyInputModel.PalletBarcode = item.PalletBarcode;
                            palletTallyInputModel.TotalNum = item.ReceivedQty;
                            palletTallyInputModel.OrderDetailId = receiving.Id;
                            palletTallyInputModel.WarehouseId = receiving.WarehouseId;
                            palletTallyInputModel.LogicPartCode = receiving.LogicalPartCode;
                            palletTallyInputModel.PalletPackage.MaterialCode = receiving.MaterialCode;
                            palletTallyInputModel.storeLocationId = cell.Id;
                            palletTallyInputModel.storeLocationCode = cell.Code;
                            palletTallyInputModel.remark = cell.Name;
                            palletTallyInputModel.storeId = m.StoreId;
                            reresult = StackingStorageService.BuildCreateStackingStorageEF(out message, palletTallyInputModel);
                            if (!reresult)
                            {
                                if (message is null)
                                {
                                    message = "保存组箱数据失败";
                                }
                                else
                                {
                                    message = message;
                                }
                                Context.TLogs.Add(new TLog()
                                {
                                    LogType = 1,
                                    ActionType = 4,
                                    Description = message,
                                    CreateDate = DateTime.Now
                                });
                                Context.SaveChanges();
                                tran.Rollback();
                                return false;
                            }
                        }

                        Context.TReceivingBills.Update(receivingBills);
                        Context.SaveChanges();
                    }
                    if (count < receivingBills.TotalQty)
                    {
                        receivingBills.Status = 1;
                        foreach (var item in m.ReceivingBillOrderDetailDtos)
                        {
                            if (item.ReceivedQty == 0 || (item.PalletBarcode is null || string.IsNullOrEmpty(item.PalletBarcode)))
                            {
                                continue;
                            }
                            var cell = cellList.Where(c => c.Code == item.StoreLocationCode).FirstOrDefault();
                            if (cell is null)
                            {
                                message = "未找到此库位";
                                tran.Rollback();
                                return false;
                            }
                            if (cell.AreaId != m.AreaId)
                            {
                                message = "库位不在一个库房中";
                                tran.Rollback();
                                return false;
                            }
                            #region 添加入库单数据
                            receivingOrder.OrderSn = receordercode;
                            //本地入库
                            receivingOrder.BillType = 1;
                            receivingOrder.WarehouseId = m.StoreId;
                            receivingOrder.AreaCode = m.AreaCode;
                            receivingOrder.AreaName = m.AreaName;
                            //receivingOrder.SupplierId = m.Suppid;
                            receivingOrder.MaterialId = item.MaterialId;
                            receivingOrder.MaterialCode = item.MaterialCode;
                            receivingOrder.MaterialName = item.MaterialName;
                            receivingOrder.OwnerId = item.OwerId;
                            receivingOrder.BatchNo = item.MaterialBatchNo;
                            receivingOrder.DeptName = item.DeptName;
                            //订单来源默认手动创建
                            receivingOrder.SourceType = 0;
                            //质检状态默认为合格
                            receivingOrder.QualityState = 1;
                            //质量状态
                            receivingOrder.Status = 3;
                            receivingOrder.ReceivedQty = 0;
                            receivingOrder.PackagedQty = 0;
                            receivingOrder.PackQty = 0;
                            receivingOrder.BatchNoExplain = item.BatchNoExplain;
                            receivingOrder.OutFactoryDate = item.OutFactoryDate;
                            receivingOrder.ProduceFactory = item.ProduceFactory;
                            receivingOrder.ProductDate = item.ProductDate;
                            receivingOrder.ExpireDate = item.ExpireDate;
                            receivingOrder.Remark = item.Remark;
                            receivingOrder.Qty = item.ReceivedQty;
                            receivingOrder.storeLocationId = cell.Code;
                            receivingOrder.relationId = item.CheckInfoId.GetValueOrDefault();
                            #region 审计字段
                            receivingOrder.CreateUserId = m.NowUserId;
                            receivingOrder.CreateUserName = m.NowUserRealName;
                            receivingOrder.CreateDate = DateTime.Now;
                            //receivingOrder.ModifyUserId = m.NowUserId;
                            //receivingOrder.ModifyUserName = m.NowUserRealName;
                            //receivingOrder.ModifyDate = DateTime.Now;
                            receivingOrder.AuditUserId = m.NowUserId;
                            receivingOrder.AuditUserName = m.NowUserRealName;
                            receivingOrder.AuditDate = DateTime.Now;
                            receivingOrder.SubmitUserId = m.NowUserId;
                            receivingOrder.SubmitUserName = m.NowUserRealName;
                            receivingOrder.SubmitDate = DateTime.Now;
                            receivingOrder.ReceivingBillId = receivingBills.Id;
                            #endregion
                            //采购订单行项目类型
                            receivingOrder.PurOrderLineType = 0;
                            receivingOrder.StackedQty = 0;
                            reresult = AddTReceivingOrderDetail(receivingOrder, out message);

                            if (reresult == false)
                            {
                                message = "添加入库单失败" + message;
                                Context.TLogs.Add(new TLog()
                                {
                                    LogType = 1,
                                    ActionType = 4,
                                    Description = message,
                                    CreateDate = DateTime.Now
                                });
                                Context.SaveChanges();
                                tran.Rollback();
                                return false;
                            }
                            #endregion
                            var receiving = Context.TReceivingOrderDetails.First(r => r.Id == receivingOrder.Id);
                            PalletTallyInputModel palletTallyInputModel = new PalletTallyInputModel();
                            palletTallyInputModel.PalletBarcode = item.PalletBarcode;
                            palletTallyInputModel.TotalNum = item.ReceivedQty;
                            palletTallyInputModel.OrderDetailId = receiving.Id;
                            palletTallyInputModel.WarehouseId = receiving.WarehouseId;
                            palletTallyInputModel.LogicPartCode = receiving.LogicalPartCode;
                            palletTallyInputModel.PalletPackage.MaterialCode = receiving.MaterialCode;
                            palletTallyInputModel.storeLocationId = cell.Id;
                            palletTallyInputModel.storeLocationCode = cell.Code;
                            palletTallyInputModel.remark = cell.Name;
                            palletTallyInputModel.storeId = m.StoreId;
                            reresult = StackingStorageService.BuildCreateStackingStorageEF(out message, palletTallyInputModel);
                            if (!reresult)
                            {
                                if (message is null)
                                {
                                    message = "保存组箱数据失败";
                                }
                                else
                                {
                                    message = message;
                                }
                                Context.TLogs.Add(new TLog()
                                {
                                    LogType = 1,
                                    ActionType = 4,
                                    Description = message,
                                    CreateDate = DateTime.Now
                                });
                                Context.SaveChanges();
                                tran.Rollback();
                                return false;
                            }
                        }
                        Context.TReceivingBills.Update(receivingBills);
                        Context.SaveChanges();
                    }
                    Context.SaveChanges();
                    //提交事务
                    tran.Commit();

                    return true;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    Context.TLogs.Add(new TLog()
                    {
                        LogType = 1,
                        ActionType = 0,
                        Description = message,
                        CreateDate = DateTime.Now
                    });
                    Context.SaveChanges();
                    throw;
                }
        }

        #region 封装方法收货入库
        /// <summary>
        /// 添加入库单管理
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTReceivingOrderDetail(TReceivingOrderDetail m, out string message)
        {
            message = "";
            //物料批次
            TMaterialKey materialKey = null;
            var materkeyobj = Context.TMaterialKeys.FirstOrDefault(x => x.BatchNo == m.BatchNo && x.MaterialId == m.MaterialId);
            if (materkeyobj != null)
            {
                materialKey = materkeyobj;
            }
            //订单来源默认手动创建
            m.SourceType = 0;
            //质检状态默认为合格
            m.QualityState = 1;
            m.ReceivedQty = 0;
            m.PackagedQty = 0;
            m.PackQty = 0;
          
            //采购订单行项目类型
            m.PurOrderLineType = 0;
            m.StackedQty = 0;
            if (materialKey == null)
            {
                TMaterialKey materkeyinsert = new TMaterialKey();
                materkeyinsert.BatchNo = m.BatchNo;
                materkeyinsert.MaterialId = m.MaterialId;
                materkeyinsert.OutFactoryDate = m.OutFactoryDate;
                materkeyinsert.OwnerId = m.OwnerId;
                materkeyinsert.OwnerName = m.OwnerName;
                materkeyinsert.ProduceFactory = m.ProduceFactory;
                materkeyinsert.ProductDate = m.ProductDate;
                materkeyinsert.Qadate = m.Qadate;
                materkeyinsert.SupplierName = m.SupplierName;
                materkeyinsert.SupplierId = m.SupplierId;
                materkeyinsert.ExpireDate = m.ExpireDate;
                materkeyinsert.CreateDate = DateTime.Now;
                materkeyinsert.MaterialCode = m.MaterialCode;
                materkeyinsert.MaterialName = m.MaterialName;
                materkeyinsert.QualityState = m.QualityState;
                materkeyinsert.DeptCode = m.DeptCode;
                materkeyinsert.DeptName = m.DeptName;
                materkeyinsert.Mblnr = m.Mblnr;
                materkeyinsert.Mjahr = m.Mjahr;
                materkeyinsert.Zeile = m.Zeile;
                materkeyinsert.ContractNo = m.ContractNo;
                materkeyinsert.PurOrderNo = m.PurOrderNo;
                materkeyinsert.PurOrderLineNo = m.PurOrderLineNo;
                materkeyinsert.PurOrderLineType = m.PurOrderLineType;
                materkeyinsert.ProOrderNo = m.ProOrderNo;
                materkeyinsert.OutOrderNo = m.OutOrderNo;
                Context.TMaterialKeys.Add(materkeyinsert);
                int result = Context.SaveChanges();
                if (result == 0)
                {
                    message = "保存失败！";

                    return false;
                }
                m.MaterialKeyId = materkeyinsert.Id;
            }
            else
            {
                m.MaterialKeyId = materialKey.Id;
                var materkey = Context.TMaterialKeys.Find(m.MaterialKeyId);
                if (materkey != null)
                {
                    materkey.BatchNo = m.BatchNo;
                    materkey.OutFactoryDate = m.OutFactoryDate;
                    materkey.OwnerId = m.OwnerId;
                    materkey.OwnerName = m.OwnerName;
                    materkey.ProduceFactory = m.ProduceFactory;
                    materkey.ProductDate = m.ProductDate;
                    materkey.Qadate = m.Qadate;
                    materkey.SupplierId = m.SupplierId;
                    materkey.SupplierName = m.SupplierName;
                    materkey.ExpireDate = m.ExpireDate;
                    materkey.MaterialCode = m.MaterialCode;
                    materkey.MaterialName = m.MaterialName;
                    materkey.QualityState = m.QualityState;
                    materkey.DeptCode = m.DeptCode;
                    materkey.DeptName = m.DeptName;
                    materkey.Mblnr = m.Mblnr;
                    materkey.Mjahr = m.Mjahr;
                    materkey.Zeile = m.Zeile;
                    materkey.ContractNo = m.ContractNo;
                    materkey.ProOrderNo = m.ProOrderNo;
                    materkey.PurOrderLineNo = m.PurOrderLineNo;
                    materkey.PurOrderLineType = m.PurOrderLineType;
                    materkey.ProOrderNo = m.ProOrderNo;
                    materkey.OutOrderNo = m.OutOrderNo;
                    Context.TMaterialKeys.Update(materkey);
                }
                int result = Context.SaveChanges();
                if (result <= 0)
                {
                    message = "保存失败！";

                    return false;
                }
            }
            Context.TReceivingOrderDetails.Add(m);
            int resultt = Context.SaveChanges();
            if (resultt > 0)
            {

                return true;
            }
            return false;
        }
        #endregion

        /// <summary>
        /// 强制完成
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool ReceivingBillComplete(int id)
        {
            using (var trans = Context.Database.BeginTransaction())
            {
                try
                {
                    var res = Context.TReceivingBills.FirstOrDefault(b => b.Id == id);
                    res.Status = 2;
                    res.EndDate = DateTime.Now;
                    Context.TReceivingBills.Update(res);
                    Context.SaveChanges();

                    var receivingBillDetails = Context.TReceivingBillDetails.Where(r => r.BillId == id).ToList();
                    foreach (var item in receivingBillDetails)
                    {
                        item.Status = 1;
                        Context.TReceivingBillDetails.Update(item);
                        Context.SaveChanges();
                    }
                    Context.SaveChanges();
                    trans.Commit();
                    return true;
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 删除收货单
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelReceivingBill(int rid)
        {
            var robj = Context.TReceivingBills.Find(rid);
            if (robj != null)
            {
                if (robj.Status == 1 || robj.Status == 2)
                {
                    return false;
                }
                Context.TReceivingBills.Remove(robj);
                Context.SaveChanges();
                return true;
            }
            return false;
        }

        /// <summary>
        /// 收获管理显示
        /// </summary>
        /// <param name="supplierId"></param>
        /// <param name="status"></param>
        /// <param name="warehouseId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Model.Models.TReceivingBill> GetReceivingBillList(int supplierId, int status, int warehouseId, int pageIndex, int pageSize, out int totalCount)
        {
            var list = Context.TReceivingBills.AsNoTracking().ToList();
            foreach (var item in list)
            {
                var rbd = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == item.Id).ToList();

                foreach (var item2 in rbd)
                {
                    item.BillDetailList = rbd;
                    if (item2.ReceivedQty <= 0)
                    {
                        continue;
                    }
                    item.ReceivedQTY = item.ReceivedQTY.GetValueOrDefault() + item2.ReceivedQty;
                }
            }
            //查找供应商
            if (supplierId != 0)
            {
                list = list.Where(x => x.SupplierId == supplierId).ToList();
            }
            //查询状态
            if (status < 3)
            {
                list = list.Where(x => x.Status == status).ToList();
            }

            //查找库房
            if (warehouseId != 0)
            {
                list = list.Where(x => x.WarehouseId == warehouseId).ToList();
            }
            totalCount = list.Count();
            list = list.OrderByDescending(x => x.CreateDate).ToList();

            return list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 根据物料分类id返回物料
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TMaterial> GetRidById(int mid)
        {
            var list = Context.TMaterials.Where(x => x.MaterialCategoryId == mid);
            return list.ToList();
        }

        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        public Model.Models.TReceivingBill GetTReceivingBillById(int rid)
        {
            var robj = Context.TReceivingBills.Find(rid);

            if (robj != null)
            {
                var rbd = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == rid).ToList();
                if (rbd != null)
                {
                    robj.BillDetailList = rbd;
                    return robj;
                }
                return robj;
            }
            return null;
        }



        /// <summary>
        /// 修改收货单
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public bool UpdReceivingBill(Model.Models.TReceivingBill m, out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    message = "";
                    //供应商信息
                    var sobj = Context.TSuppliers.Find(m.SupplierId);
                    if (sobj != null)
                    {
                        m.SupplierName = sobj.Name;
                    }

                    //仓库信息
                    var wobj = Context.TWarehouses.Find(m.WarehouseId);
                    if (wobj != null && wobj.Status==1)
                    {
                        m.WarehouseName = wobj.Name;
                        m.WarehouseCode = wobj.Code;
                    }
                    else
                    {
                        message = "库房不存在或已被禁用";
                        return false;
                    }


                    Context.TReceivingBills.Update(m);

                    #region 删除关联的订单明细
                    var mlist = Context.TReceivingBillDetails.Where(x => x.BillNo == m.BillNo && x.BillId == m.Id);
                    if (mlist != null)
                    {
                        Context.RemoveRange(mlist);
                        Context.SaveChanges();
                    }
                    #endregion

                    foreach (var item in m.BillDetailList)
                    {
                        item.Id = 0;
                        item.BillId = m.Id;
                        //关联单号
                        item.BillNo = m.BillNo;
                        //初始化状态
                        item.Status = 0;
                        //创建日期
                        item.CreateDate = DateTime.Now;
                        Context.TReceivingBillDetails.Add(item);
                    }
                    Context.SaveChanges();
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdReceivingBillStatus(int rid)
        {
            var robj = Context.TReceivingBills.Find(rid);
            if (robj != null)
            {
                robj.Status = 2;
                Context.TReceivingBills.Update(robj);
                Context.SaveChanges();
                return true;
            }
            return false;
        }
        /// <summary>
        /// 修改状态(已提交)
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdReceivingBillStatus(TReceivingBill receivingBill)
        {
            Context.TReceivingBills.Update(receivingBill);
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// RFID添加收货单
        /// </summary>
        /// <param name="addReceivingBilDTO"></param>
        /// <returns></returns>
        public bool AddCheck(AddReceivingBilDTO addReceivingBilDTO ,out string Message)
        {
            Message = "";
            using (var trans= Context.Database.BeginTransaction())
            {
                try
                {
                    var rece = Context.TReceivingBills.FirstOrDefault(r=>r.BillNo == addReceivingBilDTO.BillNo);
                    if (rece is not null)
                    {
                        trans.Rollback();
                        Message = "用相同的验收单号";
                        return false;
                    }
                    TReceivingBill receivingBill = new TReceivingBill();
                    //receivingBill.Id = addReceivingBilDTO.Id;
                    receivingBill.CreateDate = DateTime.Now;
                    receivingBill.BillNo = addReceivingBilDTO.BillNo;
                    receivingBill.Status = 0;
                    receivingBill.TotalQty = addReceivingBilDTO.addReceivingBilDetails.Sum(r => r.ReceivedQty);
                    Context.TReceivingBills.Add(receivingBill);
                    if (Context.SaveChanges() <= 0)
                    {
                        trans.Rollback();
                        Message = "添加验收单失败";
                        return false;
                    }
                    foreach (var item in addReceivingBilDTO.addReceivingBilDetails)
                    {
                        TReceivingBillDetail receivingBillDetail = new TReceivingBillDetail();
                        receivingBillDetail.BatchNo = item.BatchNo;
                        receivingBillDetail.BillNo = addReceivingBilDTO.BillNo;
                        receivingBillDetail.BillId = receivingBill.Id;
                        receivingBillDetail.MaterialCode = item.MaterialCode;
                        receivingBillDetail.MaterialName = item.MaterialName;
                        receivingBillDetail.Qty = item.ReceivedQty;
                        receivingBillDetail.ReceivedQty = 0;
                        receivingBillDetail.materialNorms = item.materialNorms;
                        receivingBillDetail.deptName = item.deptName;
                        receivingBillDetail.checkInfoId = item.checkInfoId;
                        receivingBillDetail.MaterialTypeName = item.MaterialTypeName;
                        Context.TReceivingBillDetails.Add(receivingBillDetail);
                        if (Context.SaveChanges() <= 0)
                        {
                            trans.Rollback();
                            Message = "添加验收单明细失败";
                            return false;
                        }
                    }
                    trans.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Message = ex.Message;
                    return false;
                    throw;
                }
            }
            
        }

        /// <summary>
        /// 查询全部收获单数据
        /// </summary>
        /// <returns></returns>
        public List<TReceivingBill> GetListRedceiving()
        {
            var list = Context.TReceivingBills.AsNoTracking().Where(r=>r.Status == 2).ToList();
            foreach (var item in list)
            {
                var rbd = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == item.Id).ToList();

                foreach (var item2 in rbd)
                {
                    item.BillDetailList = rbd;
                    if (item2.ReceivedQty <= 0)
                    {
                        continue;
                    }
                    item.ReceivedQTY = item.ReceivedQTY.GetValueOrDefault() + item2.ReceivedQty;
                }
            }
            return list;
        }

        /// <summary>
        /// 获取提交入库的数据
        /// </summary>
        /// <returns></returns>
        public List<SubmitPutAwayDTO> GetSubmitOutList()
        {
            var reces = Context.TReceivingBills.Where(r => r.Status != 3 && r.Status != 0).AsNoTracking().OrderBy(r=>r.CreateDate).ToList();
            if (reces is null)
            {
                return null;
            }
            List<SubmitPutAwayDTO> list = new List<SubmitPutAwayDTO>();
            foreach (var item in reces)
            {

                var rods = Context.TReceivingOrderDetails.Where(r => r.ReceivingBillId == item.Id).AsNoTracking().ToList();
                if (rods.Any(r=>r.Status != 4))
                {
                    continue;
                }
                else
                {
                    SubmitPutAwayDTO data = new SubmitPutAwayDTO()
                    {
                        checkNumber = item.BillNo,
                        storeId = item.WarehouseId.GetValueOrDefault(),
                        userId = 2064
                    };
                    List<SubmitPutAwayDetailDTO> submitPutAwayDetailDTOs = new List<SubmitPutAwayDetailDTO>();
                    foreach (var item2 in rods)
                    {
                        if (item2.Status != 4)
                        {
                            break;
                        }
                        submitPutAwayDetailDTOs.Add(new SubmitPutAwayDetailDTO()
                        {
                            count = item2.ReceivedQty.GetValueOrDefault(),
                            orderId = item2.Id,
                            storeLocationId = item2.storeLocationId,
                            remark = item2.Remark,
                            relationId = item2.relationId
                        });
                    }
                    data.items = submitPutAwayDetailDTOs;
                    list.Add(data);
                }
                
            }
            return list;
        }

        /// <summary>
        /// 可以组多个物料
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool BuildCreateStackingStorageMaterials(ReceivingBillOrderMaterialsDto m, out string message)
        {
            message = "";
            using (var tran = Context.Database.BeginTransaction())
                try
                {
                    var receivingBills = Context.TReceivingBills.FirstOrDefault(r => r.Id == m.Id);
                    if (receivingBills == null)
                    {
                        message = "收货单不存在";
                        Context.TLogs.Add(new TLog()
                        {
                            LogType = 1,
                            ActionType = 0,
                            Description = "收货单不存在",
                            CreateDate = DateTime.Now
                        });
                        Context.SaveChanges();
                        return false;
                    }
                    var rbd = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == receivingBills.Id).ToList();

                    foreach (var item in rbd)
                    {

                        if (item.ReceivedQty <= 0)
                        {
                            continue;
                        }
                        receivingBills.ReceivedQTY = receivingBills.ReceivedQTY.GetValueOrDefault() + item.ReceivedQty;
                    }
                    string receordercode = "";

                    //查看收货单已收货数量是否是0 （是的话创建一个入库单编号 不是0查询出入库单编号）
                    if (receivingBills.ReceivedQTY == 0 || receivingBills.ReceivedQTY is null)
                    {
                        receivingBills.WarehouseId = m.StoreId;
                        // 不用在赋值库区 因为一个验收单的商品可以放在不同的库区
                        //receivingBills.AreaId = m.AreaId;
                        //receivingBills.AreaName = m.AreaName;
                        //receivingBills.AreaCode = m.AreaCode; 
                        Context.TReceivingBills.Update(receivingBills);
                        if (Context.SaveChanges() <= 0)
                        {
                            message = "修改库区信息失败";
                            tran.Rollback();
                            return false;
                        }
                        receordercode = BarCodeRuleRepository.GetBarCodeSample(1);
                        if (string.IsNullOrEmpty(receordercode) || receordercode.Length == 0)
                        {
                            message = "入库单编码不存在或已被禁用！";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "入库单编码不存在或已被禁用",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                    }
                    else
                    {
                        // 不用判断了 因为一个验收单的商品可以放在不同的库区
                        //if (receivingBills.AreaId != m.AreaId)
                        //{
                        //    message = "不在一个库房";
                        //    Context.TLogs.Add(new TLog()
                        //    {
                        //        LogType = 1,
                        //        ActionType = 0,
                        //        Description = "不在一个库房",
                        //        CreateDate = DateTime.Now
                        //    });
                        //    Context.SaveChanges();
                        //    tran.Rollback();
                        //    return false;
                        //}
                        var rece = Context.TReceivingOrderDetails.AsNoTracking().FirstOrDefault(r => r.ReceivingBillId == receivingBills.Id);
                        if (rece is null)
                        {
                            message = "入库单编码不存在！";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "入库单编码不存在",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                        receordercode = rece.OrderSn;
                    }
                    decimal count = 0;//计算数量
                    foreach (var item in m.ReceivingBillOrderMaterialsDetailDto)
                    {
                        if (item.ReceivedQty < 0)
                        {
                            message = "收货数量不能小于0";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "收货数量不能小于0",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                        var r = Context.TReceivingBillDetails.Find(item.ReceivingBillDetailId);
                        if (r is null)
                        {
                            message = "收货单明细不存在";
                            Context.TLogs.Add(new TLog()
                            {
                                LogType = 1,
                                ActionType = 0,
                                Description = "收货单明细不存在",
                                CreateDate = DateTime.Now
                            });
                            Context.SaveChanges();
                            tran.Rollback();
                            return false;
                        }
                        else
                        {
                            item.MaterialName = r.MaterialName;
                            item.MaterialBatchNo = r.BatchNo;
                            item.DeptName = r.deptName;
                            item.CheckInfoId = r.checkInfoId;
                            r.storeLocationId = m.StoreLocationId;
                            Context.TReceivingBillDetails.Update(r);
                            if (Context.SaveChanges() <= 0)
                            {
                                message = "修改收获单明细仓位失败";
                                tran.Rollback();
                                return false;
                            }

                            if (r.Qty >= item.ReceivedQty && (r.ReceivedQty + item.ReceivedQty) <= r.Qty)
                            {
                                r.ReceivedQty += item.ReceivedQty;
                                count += item.ReceivedQty;
                                if (r.Price is not null || r.Price >= 0)
                                {
                                    receivingBills.TotalPrice += (decimal)r.Price * item.ReceivedQty;
                                }
                            }
                            else
                            {
                                message = "收货数量不能大于物料数量";
                                Context.TLogs.Add(new TLog()
                                {
                                    LogType = 1,
                                    ActionType = 0,
                                    Description = "收货数量不能大于物料数量",
                                    CreateDate = DateTime.Now
                                });
                                Context.SaveChanges();
                                tran.Rollback();
                                return false;
                            }
                            Context.TReceivingBillDetails.Update(r);
                            Context.SaveChanges();
                        }
                    }
                    //TReceivingOrderDetail receivingOrder = new TReceivingOrderDetail();
                    bool reresult = false;
                    var res = Context.TReceivingBillDetails.Where(x => x.BillId == receivingBills.Id).ToList();
                    var cellList = Context.TCells.AsNoTracking().ToList();
                    // 计算收货数量
                    foreach (var item in rbd)
                    {
                        count += item.ReceivedQty;
                    }
                   
                    if (count == receivingBills.TotalQty)
                    {

                        reresult = AddReceivingOrderDeatils(m, receordercode, out message);
                        if (!reresult)
                        {
                            message = message;
                            tran.Rollback();
                            return false;
                        }
                        receivingBills.Status = 2;
                        receivingBills.EndDate = DateTime.Now;

                        Context.TReceivingBills.Update(receivingBills);
                        if (Context.SaveChanges() <= 0)
                        {
                            message = "修改收货单失败";
                            tran.Rollback();
                            return false;
                        }
                        var cell = Context.TCells.FirstOrDefault(c=>c.Code == m.StoreLocationId);
                        if (cell is null)
                        {
                            message = "未找到此库位";
                            tran.Rollback();
                            return false;
                        }
                        cell.BusinessType = (int)EmBusinessType.In;
                        cell.IsLock = true;
                        cell.FullStatus = 1;
                        cell.Status = (int)EmCellStatus.Lock;
                        cell.ModifyDate = DateTime.Now;
                        Context.TCells.Update(cell);

                        if (Context.SaveChanges() <= 0)
                        {
                            message = "仓位锁定失败";
                            tran.Rollback();
                            return false;
                        }

                    }
                    if (count < receivingBills.TotalQty)
                    {
                        reresult =  AddReceivingOrderDeatils(m, receordercode, out message);
                        if (!reresult)
                        {
                            message = message;
                            tran.Rollback();
                            return false;
                        }
                        receivingBills.Status = 1;
                        Context.TReceivingBills.Update(receivingBills);
                        if (Context.SaveChanges() <= 0)
                        {
                            message = "修改收货单失败";
                            tran.Rollback();
                            return false;
                        }

                        var cell = Context.TCells.FirstOrDefault(c => c.Code == m.StoreLocationId);
                        if (cell is null)
                        {
                            message = "未找到此库位";
                            tran.Rollback();
                            return false;
                        }
                        cell.BusinessType = (int)EmBusinessType.In;
                        cell.IsLock = true;
                        cell.FullStatus = 1;
                        cell.Status = (int)EmCellStatus.Lock;
                        cell.ModifyDate = DateTime.Now;
                        Context.TCells.Update(cell);

                        if (Context.SaveChanges() <= 0)
                        {
                            message = "仓位锁定失败";
                            tran.Rollback();
                            return false;
                        }
                    }
                    Context.SaveChanges();
                    //提交事务
                    tran.Commit();

                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    Context.TLogs.Add(new TLog()
                    {
                        LogType = 1,
                        ActionType = 0,
                        Description = message + ex.Message,
                        CreateDate = DateTime.Now
                    });
                    Context.SaveChanges();
                    return false;
                    throw;
                }
        }
        /// <summary>
        /// 添加入库单的方法仅本类使用
        /// </summary>
        /// <param name="m"></param>
        /// <param name="receordercode"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private bool AddReceivingOrderDeatils(ReceivingBillOrderMaterialsDto m,string receordercode, out string message)
        {
            var cellList = Context.TCells.AsNoTracking().ToList();
            var cell = cellList.Where(c => c.Code == m.StoreLocationId).FirstOrDefault();
            bool reresult = false;
            message = "";
            foreach (var item in m.ReceivingBillOrderMaterialsDetailDto)
            {
                TReceivingOrderDetail receivingOrder = new TReceivingOrderDetail();
                if (cell is null)
                {
                    message = "未找到此库位";
                    return false;
                }
                #region 添加入库单数据
                receivingOrder.OrderSn = receordercode;
                //本地入库
                receivingOrder.BillType = 1;
                receivingOrder.WarehouseId = m.StoreId;
                //receivingOrder.SupplierId = m.Suppid;
                receivingOrder.MaterialId = item.MaterialId;
                receivingOrder.MaterialCode = item.MaterialCode;
                receivingOrder.MaterialName = item.MaterialName;
                receivingOrder.OwnerId = item.OwerId;
                receivingOrder.BatchNo = item.MaterialBatchNo;
                receivingOrder.DeptName = item.DeptName;
                //订单来源默认手动创建
                receivingOrder.SourceType = 0;
                //质检状态默认为合格
                receivingOrder.QualityState = 1;
                //质量状态
                receivingOrder.Status = 3;
                receivingOrder.ReceivedQty = 0;
                receivingOrder.PackagedQty = 0;
                receivingOrder.PackQty = 0;
                receivingOrder.BatchNoExplain = item.BatchNoExplain;
                receivingOrder.OutFactoryDate = item.OutFactoryDate;
                receivingOrder.ProduceFactory = item.ProduceFactory;
                receivingOrder.ProductDate = item.ProductDate;
                receivingOrder.ExpireDate = item.ExpireDate;
                receivingOrder.Remark = item.Remark;
                receivingOrder.Qty = item.ReceivedQty;
                receivingOrder.storeLocationId = cell.Erpcode;
                receivingOrder.relationId = item.CheckInfoId.GetValueOrDefault();
                #region 审计字段
                receivingOrder.CreateUserId = m.NowUserId;
                receivingOrder.CreateUserName = m.NowUserRealName;
                receivingOrder.CreateDate = DateTime.Now;
                //receivingOrder.ModifyUserId = m.NowUserId;
                //receivingOrder.ModifyUserName = m.NowUserRealName;
                //receivingOrder.ModifyDate = DateTime.Now;
                receivingOrder.AuditUserId = m.NowUserId;
                receivingOrder.AuditUserName = m.NowUserRealName;
                receivingOrder.AuditDate = DateTime.Now;
                receivingOrder.SubmitUserId = m.NowUserId;
                receivingOrder.SubmitUserName = m.NowUserRealName;
                receivingOrder.SubmitDate = DateTime.Now;
                receivingOrder.ReceivingBillId = m.Id;
                #endregion
                //采购订单行项目类型
                receivingOrder.PurOrderLineType = 0;
                receivingOrder.StackedQty = 0;
                reresult = AddTReceivingOrderDetail(receivingOrder, out message);

                if (reresult == false)
                {
                    message = "添加入库单失败" + message;
                    return false;
                }
                #endregion
                var receiving = Context.TReceivingOrderDetails.First(r => r.Id == receivingOrder.Id);
                PalletTallyInputModel palletTallyInputModel = new PalletTallyInputModel();
                palletTallyInputModel.PalletBarcode = m.PalletBarcode;
                palletTallyInputModel.TotalNum = item.ReceivedQty;
                palletTallyInputModel.OrderDetailId = receiving.Id;
                palletTallyInputModel.WarehouseId = receiving.WarehouseId;
                palletTallyInputModel.LogicPartCode = receiving.LogicalPartCode;
                palletTallyInputModel.PalletPackage.MaterialCode = receiving.MaterialCode;
                palletTallyInputModel.storeLocationId = Convert.ToInt32(cell.Erpcode);
                palletTallyInputModel.storeLocationCode = cell.Code;
                palletTallyInputModel.remark = cell.Name;
                palletTallyInputModel.storeId = m.StoreId;
                reresult = StackingStorageService.BuildCreateStackingStorageMaterials(out message, palletTallyInputModel);
                if (!reresult)
                {
                    if (message is null)
                    {
                        message = "保存组箱数据失败";
                    }
                    else
                    {
                        message = message;
                    }
                    return false;
                }
            }
            return true;
        }

        public TReceivingBill GetCheckMaterialCode(string ChackNumber)
        {
            var robj = Context.TReceivingBills.FirstOrDefault(r=>r.BillNo == ChackNumber);

            if (robj != null)
            {
                var rbd = Context.TReceivingBillDetails.AsNoTracking().Where(x => x.BillId == robj.Id).ToList();
                if (rbd != null)
                {
                    robj.BillDetailList = rbd;
                    return robj;
                }
                return robj;
            }
            return null;
        }

        //private bool AreaSplit(string OldArea, string NewArea, out string message)
        //{
        //    message = "";
        //    if (OldArea == null || NewArea == null)
        //    {
        //        message = "库房为空";
        //        return false;
        //    }
        //    string[] parts1 = NewArea.Split('-');
        //    string result1 = parts1[1]; 

        //}
    }
}
